package team.product.bean;

import model.Member;
import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.Logger;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.SocialAuthUtil;
import team.product.utils.FaceUtils;
import team.product.wapper.ForumRequestWrapper;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * User: Lương Xuân Huy
 * Date: 9/17/14
 * Time: 4:09 PM
 * Long Van Soft Solution Sjc.
 * To change this template use File | Settings | File and Code Templates
 */
@ManagedBean(name = "Authenticate")
@SessionScoped
public class AuthenticateBean extends BaseFrontBean {
    private Logger logger = Logger.getLogger(getClass());
    private boolean loginCheck = false;

    private SocialAuthConfig config;
    private SocialAuthManager socialAuthManager;
    private static final String oAuthProperties = "oauth_consumer.properties";
    private Profile socialProfile = null;

    private String u;

    public String getU() {
        return u;
    }

    public void setU(String u) {
        this.u = u;
    }

    HttpSession session = FaceUtils.getSession();

    public boolean isLoginCheck() {
        return loginCheck;
    }

    public void setLoginCheck(boolean loginCheck) {
        this.loginCheck = loginCheck;
    }

    public void onLoad() {
        try {
            u = (String) FaceUtils.getSession().getAttribute("username");
            if (isLoginCheck() == false) {
                ForumRequestWrapper requestWrapper = new ForumRequestWrapper(FaceUtils.getRequest());
                String redirectUrl = (String) session.getAttribute("socialRedirectUrl");
                String fb_id = requestWrapper.getParameter("fb_id_auto_login");
                if (null != fb_id) {
                    fBAutoLogin(fb_id, requestWrapper);
                } else {
                    if (null == socialAuthManager) socialAuthManager = getSocialAuthManagerFromSession();
                    AuthProvider authProvider = getSocialAuthManagerFromSession().connect(SocialAuthUtil.getRequestParametersMap(FaceUtils.getRequest()));
                    if (getSocialAuthManagerFromSession().isConnected(authProvider.getProviderId())) {
                        logger.info("connected with social network : " + authProvider.getProviderId());
                        socialProfile = getSocialAuthManagerFromSession().getCurrentAuthProvider().getUserProfile();
                        String email_check = socialProfile.getEmail();
                        Member member = getMemberManager().getMemberByEmail(email_check);
                        if (null == member) {
                            registerWithSocial(member, getSocialProfile());
                        } else {
                            String socialId = getSocialId(member, getSocialProfile().getProviderId());
                            if (GenericValidator.isBlankOrNull(socialId) || "0".equals(socialId)) {
                                registerWithSocial(member, getSocialProfile());
                            }
                            loginWithSocial(member.getEmail(), requestWrapper);
                            session.setAttribute("username", member.getUsername());
                            if (null != redirectUrl)
                                FacesContext.getCurrentInstance().getExternalContext().redirect(redirectUrl);
                            logger.info("Login Social Success!");
                        }
                    } else {
                        logger.info("can't loged with social network account " + getSocialAuthManagerFromSession().getCurrentAuthProvider().getProviderId() + ": return information is not enough to verify!");
                    }
                }
            }
        } catch (Exception e) {
            logger.warn(" social verify error : " + e.getMessage());
        }
    }

    public void updateId(ActionEvent ae) {
        socialLogin();
        try {
            String btnClicked = ae.getComponent().getId();
            if (btnClicked.contains("facebook")) btnClicked = "facebook";
            if (btnClicked.contains("google")) btnClicked = "googleplus";
            if (btnClicked.contains("twitter")) btnClicked = "twitter";
            if (null != socialAuthManager && btnClicked.length() > 1) {
                logger.info("social login for : " + btnClicked);
                String url_Redirect = getRedirectAuthUrl();
                if (btnClicked.contains("google")) {
                    url_Redirect = "http://localhost:8080/index.xhtml";
                }
                session.setAttribute("socialRedirectUrl", getRedirectAuthUrl());
                String url = socialAuthManager.getAuthenticationUrl(btnClicked, url_Redirect);
                FacesContext.getCurrentInstance().getExternalContext().redirect(url);
            }
        } catch (Exception ex) {
            logger.warn("Social Login Error : " + ex.getMessage());
        }
    }

    public void socialLogin() {
        try {
            if (null == config) {
                config = SocialAuthConfig.getDefault();
                config.load(getClass().getClassLoader().getResourceAsStream(oAuthProperties));
            }
            if (null == socialAuthManager) {
                socialAuthManager = new SocialAuthManager();
                socialAuthManager.setSocialAuthConfig(config);
            }
            session.setAttribute("socialAuthManager", socialAuthManager);
        } catch (Exception ex) {
            logger.info("Load Social Authenticate config Error : " + ex.getMessage());
        }
    }

    public String registerWithSocial(Member member, Profile p) {
        if (null == member)
            member = new Member();
        try {
            if (p.getProviderId().equals("twitter"))
                p.setEmail("twitter_bdn@.vn");
            member.setEmail(p.getEmail());
//            if (p.getProviderId().equals("googleplus"))
//                if (p.getProviderId().equals("twitter"))
            if (p.getProviderId().equals("facebook"))
                member.setFb_uid(p.getValidatedId());
            if (null == p.getDisplayName()) {
                p.setDisplayName(p.getFullName());
            }
            member.setUsername(p.getDisplayName());
            member.setAvatar(p.getProfileImageURL());
            getMemberManager().createMember(member);
            logger.info("Update Member Register With MXH Success!");
            setLoginCheck(true);
        } catch (Exception ex) {
            logger.error("Register social Error!!!" + ex.getMessage());
        }
        return null;
    }

    public void loginWithSocial(String email, ForumRequestWrapper requestWrapper) {
        if (null != email) {
            try {
                Member member = null;
                member = getMemberManager().getMemberByEmail(email);
                logger.info("Website Login set UserSession Success!");
                setLoginCheck(true);
            } catch (Exception e) {
                logger.error("Website Login set UserSession Error!!!");
            }
        }
    }

    public void fBAutoLogin(String fb_id, ForumRequestWrapper requestWrapper) {
        if (isLoginCheck() == false) {
            if (null != fb_id && !fb_id.isEmpty()) {
                try {
                    Integer memberId = getMemberManager().getMemberIdByUid(fb_id, "facebook");
                    if (memberId == 0) {
                        logger.warn("User chua co trong he thong");
                        return;
                    }
                    // Dang nhap + set Session
                    Member member = null;
                    member = getMemberManager().getMemberById(memberId);
                    logger.info("Auto Fb To Website Login set UserSession Success!");
                    setLoginCheck(true);
                } catch (Exception e) {
                    logger.error("Auto Fb To Website Login set UserSession Error!!!");
                }
            }
        }
    }

    public String logout() {
        session.removeAttribute("username");
        logger.info("Logout Session !");
        setLoginCheck(false);
        return null;
    }

    public String getRedirectAuthUrl() {
        HttpServletRequest request = FaceUtils.getRequest();
        String httpURL = "http://";
        String host = request.getHeader("host");
        String uri = request.getRequestURI();
        return httpURL + host + uri;
    }

    public SocialAuthManager getSocialAuthManagerFromSession() {
        if (null == socialAuthManager) {
            HttpSession session = FaceUtils.getSession();
            socialAuthManager = (SocialAuthManager) session.getAttribute("socialAuthManager");
        }
        return socialAuthManager;
    }

    public String getSocialId(Member members, String key) {
        int value = ("facebook".equals(key) ? 1 : 0) + ("googleplus".equals(key) ? 1 : 0) * 2 + ("twitter".equals(key) ? 1 : 0) * 4;
        switch (value) {
            case 1:
                return "" + members.getFb_uid();
            case 2:
                return null;
            case 4:
                return null;
            default:
                return null;
        }
    }

    public Profile getSocialProfile() {
        return socialProfile;
    }

    public void setSocialProfile(Profile socialProfile) {
        this.socialProfile = socialProfile;
    }
}
